// public/js/tictactoe-game.js

export function init(socket, state) {
    // DOM 元素
    const currentRoomIdSpan = document.getElementById('current-room-id');
    const messageArea = document.getElementById('tictactoe-game-message-area');
    const gameCanvas = document.getElementById('tictactoe-game-canvas');
    const leaveGameBtn = document.getElementById('leave-tictactoe-game-btn');
    let roomId = state.roomId;
    let myMark = '';

    const controller = new AbortController();
    const { signal } = controller;

    updateMessage('游戏开始！');
    initGameUI(state);

    socket.on('game_state_updated', updateGameState);

    function handleClick(event) {
        const clickedButton = event.target;

        if (clickedButton.id === 'leave-tictactoe-game-btn') {
            console.log('离开游戏按钮被点击');
            socket.emit('leave_game', { roomId: roomId });
        } 
    }

    leaveGameBtn.addEventListener('click', handleClick, { signal });
    socket.on('game_left_success', leaveGame);

    // 辅助函数
    function initGameUI(data) {
        let boardHtml = '<div class="tic-tac-toe-board">';
        for (let i = 0; i < 9; i++) {
            boardHtml += `<div class="tic-tac-toe-cell" data-position="${i}"></div>`;
        }
        boardHtml += '</div>';
        gameCanvas.innerHTML = boardHtml;

        console.log("data:",data);
        myMark = data.state.mark;

        updateGameState(data.state.common);

        function handleCellClick(event) 
        {
            // event.target 就是被点击的 cell 元素
            const cell = event.target;
            const position = cell.dataset.position;

            if (cell.textContent) 
            {
                    updateMessage("该位置已经有棋子了");
                    return;
            }

            console.log(`单元格 ${position} 被点击`);

            // 确保在点击时 myMark 已经被设置
            if (myMark) {
                socket.emit('game_action', {
                    roomId: roomId,
                    action: 'place_mark',
                    actionData: { position: position, mark: myMark }
                });
            } else {
                console.warn('警告：myMark 尚未被设置，无法发送游戏动作。');
            }
        }

        // 添加点击事件
        document.querySelectorAll('.tic-tac-toe-cell').forEach(cell => {
            cell.addEventListener('click',  handleCellClick, { signal });
        });
    }

    function updateGameState(data)
    {
        console.log("updateGameState's data:", data);
        if(data.position)
        {
            console.log("data.sate.position:", data.position);
            updateMessage(`在位置 ${data.position} 落子`);
        }

         document.querySelectorAll('.tic-tac-toe-cell').forEach(cell => {
            cell.textContent = data.board[cell.dataset.position];
        });
    }

    function leaveGame(data)
    {
        const navigatePath = `room.html?roomId=${encodeURIComponent(roomId)}`;
        const navigateEvent = new CustomEvent('navigate', {
                    detail: { 
                        path: navigatePath
                    }
                });

        window.dispatchEvent(navigateEvent);
    }

    function updateMessage(text, color = 'inherit') {
        messageArea.textContent = text;
        messageArea.style.color = color;
     }

     window.tictactoeController = controller;
}

export function cleanup(socket) {
console.log('tictactoe-game module cleaned up.');
    if (window.tictactoeController) {
        window.tictactoeController.abort();
        console.log('tictactoe event listeners have been aborted.');
        delete window.tictactoeController;
    }

    socket.off('game_state_updated');
    socket.off('leave_game');
}